package com.zhss.concurrency.deadlock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName SolutionOne
 * @Description TODO
 * @Author leejiliang
 * @DateTime 2021/9/1 14:18
 * @Version 1.0
 */
public class SolutionOne {
	public static void main(String[] args) throws InterruptedException {

		Lock lock1 = new ReentrantLock();
		Lock lock2 = new ReentrantLock();



		Thread t1 = new Thread(() -> {
			lock1.lock();
			try {
				Thread.sleep(1000L);

				System.out.println(Thread.currentThread().getName()+" 持有锁1, 尝试获取锁2");
				lock2.lock();
				System.out.println(Thread.currentThread().getName()+" 持有锁1, 获取锁2成功");
			} catch (InterruptedException e) {
				e.printStackTrace();
			}finally {
				lock2.unlock();
				lock1.unlock();
			}
		});
		Thread t2 = new Thread(() -> {
			lock2.lock();
			try {
				Thread.sleep(1000L);

				System.out.println(Thread.currentThread().getName()+" 持有锁2, 尝试获取锁1");
				lock1.lock();
				System.out.println(Thread.currentThread().getName()+" 持有锁2, 获取锁1成功");
			} catch (InterruptedException e) {
				e.printStackTrace();
			}finally {
				lock1.unlock();
				lock2.unlock();
			}
		});

		t1.start();
		t2.start();
		t1.join();
	}
}
